
Skt.Group = L.Class.extend({
	
	includes: L.Mixin.Events,
	
	events: ['update','roomListUpdate','roomModeratorUpdate','roomObjectAction'],

	initialize: function(id, name, type, ownerId, groupsManager) {
		this._id = id;
		this._name = name;
		this._type = type;
		this._ownerId = Number(ownerId);
		this._groupsManager = groupsManager;
		
		this._members = [ this._ownerId ];
		
		this._roomList = new Skt.RoomList(
			Skt.SlideType.GROUP, 
			this._groupsManager.getSketchpad(), 
			this
		);
		
		this._roomList.on('update', this._roomListUpdate, this);
		this._roomList.on('roomModeratorUpdate', this._roomModeratorUpdate, this);
		this._roomList.on('roomObjectAction', this._roomObjectAction, this);

		this._couple(this._groupsManager.getSketchpad().getOptions().coupling);
	},
	
	addMember: function( userId ) {
		var self = this;
		
		if ( !self.isMember(userId) ) {
			self._members.push(Number(userId));
			
			self.fire('update',{
				action: 'addMember',
				userId: Number(userId),
				group: self
			});
		}
	},
	
	isOwner: function(userId) {
		return this._ownerId == Number(userId);
	},
 	
	isMember: function(userId) {
		return $.inArray(Number(userId), this._members) >= 0;
	},
	
	canInvite: function(userId) {
		return this._groupType == Skt.GroupType.NOTES && this.isMember(userId);
	},
	
	getName: function() {
		return this._name;
	},
	
	getType: function() {
		return this._type;
	},
	
	getOwnerId: function() {
		return this._ownerId;
	},
	
	getMembers: function() {
		return this._members;
	},
	
	getRoomList: function() {
		return this._roomList;
	},
	
	getId: function() {
		return this._id;
	},
	
	getState: function() {
		var self = this;
		return { members: self._members };
	},
	
	setState: function( state ) {
		var self = this;
		if ( state.members ) {
			self._members = state.members;
			self.fire('update',{
				action: 'setState',
				group: self
			});
		}
	},
	
	_roomListUpdate: function(params) {
		var self = this;
		self.fire('roomListUpdate', params); 
	},
	_roomModeratorUpdate: function(params) {
		var self = this;
		self.fire('roomModeratorUpdate', params); 
	},
	_roomObjectAction: function(params) {
		var self = this;
		self.fire('roomObjectAction', params); 
	},
	
	_couple: function( coupling ) {
		if ( coupling.enabled ) {
			coupling.activityAdapter.coupleObject(
				"group" + this._id,
				this,
				{
					messageType: "STATE",
					explicitMapping: ["addMember"]
				}
			);
		}
	}
	
});

Skt.Group.findSelf = function(group) {
	return Skt.sketchpad.getGroupsManager().findGroup(group._id);
};

